package com.cskaoyan.service;

import com.cskaoyan.bean.model.MarketCoupon;
import com.cskaoyan.bean.model.MarketCouponExample;
import com.cskaoyan.bean.model.MarketCouponUser;
import com.cskaoyan.bean.model.MarketCouponUserExample;
import com.cskaoyan.mapper.MarketCouponMapper;
import com.cskaoyan.mapper.MarketCouponUserMapper;
import com.cskaoyan.util.CouponConstant;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class CouponServiceImpl implements CouponService{
    @Autowired
    MarketCouponMapper couponMapper;
    @Autowired
    MarketCouponUserMapper couponUserMapper;

    @Override
    public List queryList(int page, int limit) {
        MarketCouponExample example = new MarketCouponExample();
        return queryList(example, page, limit, "add_time", "desc");
    }
    public List<MarketCoupon> queryList(MarketCouponExample example, int offset, int limit, String sort, String order) {
        MarketCouponExample.Criteria criteria = example.createCriteria();
        criteria.andTypeEqualTo(CouponConstant.TYPE_COMMON).andStatusEqualTo(CouponConstant.STATUS_NORMAL).andDeletedEqualTo(false);

        example.setOrderByClause(sort + " " + order);
        PageHelper.startPage(offset, limit);
        return couponMapper.selectByExample(example);
    }

    @Override
    public List queryAvailableList(Integer userId, int page, int limit) {
        assert userId != null;
        // 过滤掉登录账号已经领取过的coupon
        MarketCouponExample example = new MarketCouponExample();
        MarketCouponExample.Criteria c = example.createCriteria();
        MarketCouponUserExample couponUserExample = new MarketCouponUserExample();
        MarketCouponUserExample.Criteria criteria = couponUserExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        List<MarketCouponUser> used = couponUserMapper.selectByExample(couponUserExample);
        if(used!=null && !used.isEmpty()){
            c.andIdNotIn(used.stream().map(MarketCouponUser::getCouponId).collect(Collectors.toList()));
        }
        return queryList(example, page, limit, "add_time", "desc");
    }

    @Override
    public MarketCoupon findById(Integer couponId) {

        MarketCouponExample example = new MarketCouponExample();
        example.createCriteria().andIdEqualTo(couponId)
                .andDeletedEqualTo(false)
                .andStatusEqualTo((short) 0);

        List<MarketCoupon> couponList = couponMapper.selectByExample(example);
        return couponList.size() > 0 ? couponList.get(0) : null;
    }
}
